const sqlite = require("./sqlite");
const fs = require("fs");

const tableName = 't_user'

exports.queryData = (params) => {
  let sql = `select * from ${tableName}`
  if (params) {
    let condition = "";
    Object.keys(params).forEach(key => {
      const value = params[key]
      if (!value || value === '') {
        return
      }
      if (condition != "") {
        if (typeof(value) == 'string') {
          condition += ` AND ${key} = '${value}'`
        } else {
          condition += ` AND ${key} = ${value}`
        }
      } else {
        if (typeof(value) == 'string') {
          condition += ` ${key} = '${value}'`
        } else {
          condition += ` ${key} = ${value}`
        }
      }
    });
    if (condition != "") {
      sql += ` where ${condition}`
    }
    console.log('[Query] =======>', sql)
  }
  return sqlite.executeQuery({sql: sql});
};
 
exports.insertData = (data) => {
  return sqlite.executeInsert({table: tableName, data});
};

exports.updateData = (data) => {
  const id = data.id
  delete data.id;
  let avatarBuffer = null;
  let avatar = data.avatar
  // 确保 `avatar` 是 Base64
  if (avatar && avatar.startsWith("data:image")) {
    const base64Data = avatar.split(",")[1]; // 去掉 "data:image/png;base64," 部分
    avatarBuffer = Buffer.from(base64Data, "base64"); // 转换为 Buffer 存入 SQLite
    data.avatarBuffer = avatarBuffer
  }
  return sqlite.executeUpdate({table: tableName, data, condition: `id = ${id}`});
};

exports.deleteData = (id) => {
  return sqlite.executeDelete({table: tableName, condition: `id = ${id}`});
};
